package cn.kuporo.seckill.stock.infrastructure.repository;

import cn.hutool.core.collection.CollectionUtil;
import cn.kuporo.seckill.common.model.enums.SeckillStockBucketStatus;
import cn.kuporo.seckill.stock.domain.model.entity.SeckillStockBucket;
import cn.kuporo.seckill.stock.domain.repository.SeckillStockBucketRepository;
import cn.kuporo.seckill.stock.infrastructure.mapper.SeckillStockBucketMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;

/**
 * @author: kuporo
 * @since: 2025/8/1
 * @description: 分桶库存Repository实现类
 */
@Component
@RequiredArgsConstructor
public class SeckillStockBucketRepositoryImpl implements SeckillStockBucketRepository {
    private final SeckillStockBucketMapper seckillStockBucketMapper;

    /**
     * 暂停库存
     */
    @Override
    public boolean suspendBuckets(Long goodsId) {
        if (goodsId == null){
            return false;
        }
        int count = seckillStockBucketMapper.updateStatusByGoodsId(SeckillStockBucketStatus.DISABLED.getCode(), goodsId);
        return true;
    }

    /**
     * 根据商品id获取库存分桶列表
     */
    @Override
    public List<SeckillStockBucket> getBucketsByGoodsId(Long goodsId) {
        if (goodsId == null){
            return Collections.emptyList();
        }
        return seckillStockBucketMapper.getBucketsByGoodsId(goodsId);
    }

    @Override
    public boolean resumeBuckets(Long goodsId) {
        if (goodsId == null){
            return false;
        }
        int count = seckillStockBucketMapper.updateStatusByGoodsId(SeckillStockBucketStatus.ENABLED.getCode(), goodsId);
        return true;
    }

    @Override
    public boolean submitBuckets(Long goodsId, List<SeckillStockBucket> buckets) {
        if (goodsId == null || CollectionUtil.isEmpty(buckets)){
            return false;
        }
        seckillStockBucketMapper.deleteByGoodsId(goodsId);
        seckillStockBucketMapper.insertBatch(buckets);
        return true;
    }

    @Override
    public boolean decreaseStock(Integer quantity, Integer serialNo, Long goodsId) {
        if (quantity == null || serialNo == null || goodsId == null){
            return false;
        }
        seckillStockBucketMapper.decreaseStock(quantity, serialNo, goodsId);
        return true;
    }
}
